<template>
    <div class="app-container" ref="main">

        <el-container>
            <el-header>
                <section class="search_box clearfix"
                         :class="{'searchStatus': this.$store.state.app.sidebar.searchStatus}">
                    <el-row>

                        <el-col :md="12" :lg="8" :xl="6">
                            <label class="search-label">新闻标题：</label>
                            <el-input v-model="listQuery.newsTitle" @keyup.enter.native="search" size="mini"
                                      class="search-input" placeholder="请输入新闻标题"
                                      clearable @change="search"></el-input>
                        </el-col>

                        <el-col :md="12" :lg="8" :xl="6">
                            <label class="search-label ">新闻类型：</label>
                            <el-select v-model="listQuery.newsType" @keyup.enter.native="search"
                                       placeholder="全部" clearable
                                       class="search-input" size="mini" @change="search">
                                <el-option v-for="item in newsTypeOptions" :key="item.value" :label="item.label"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-col>

                        <el-col :md="24" :lg="8" :xl="12" class="text_right">
                            <el-button @click="openDialog('create')" icon="el-icon-edit" type="primary" size="mini">添加
                            </el-button>
                        </el-col>
                    </el-row>
                </section>
            </el-header>
            <el-main>
                <el-table :data="list" border fit highlight-current-row
                          :max-height="listHeight">

                    <el-table-column align="center" label="序号" prop="index" width="70">
                    </el-table-column>

                    <el-table-column align="center" label="新闻标题" prop="newsTitle" min-width="100">
                        <template slot-scope="scope">
                            <el-button type="text" @click="openDialog('update',scope.row)" size="mini">
                                {{scope.row.newsTitle}}
                            </el-button>
                        </template>
                    </el-table-column>

                    <el-table-column align="center" label="新闻类型" prop="newsType" min-width="80">
                        <template slot-scope="scope">
                     <span v-for="(item,index) in newsTypeOptions" :key="index"
                           v-if="scope.row.newsType === item.value">
                        {{item.label}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column align="center" label="新闻来源" prop="newsSource" min-width="80">
                    </el-table-column>

                    <el-table-column align="center" label="时间" prop="newsTime" min-width="80">
                    </el-table-column>

                    <el-table-column align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button type='danger' size="mini"
                                       @click="del(scope.row.keyId)">删除
                            </el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </el-main>
            <el-footer>
                <!--翻页-->
                <div class="pagination-container">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                   :current-page.sync="currentPage"
                                   :page-size="listQuery.pageSize" :total="totalElements"
                                   :page-sizes="[10, 20, 50, 100]"
                                   layout="total, sizes, prev, pager, next, jumper" background>
                    </el-pagination>
                </div>
            </el-footer>
        </el-container>

        <!--添加弹出框-->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="70%">
            <el-form :model="temp" :rules="tempRules" ref="temp" label-width="130px"
                     v-loading="dialogFormVisibleLoading">
                <el-tabs :tab-position="tabPosition" v-model="tabValue">
                    <el-tab-pane label="基础属性" name="first">
                        <el-row class="form_box">
                            <el-col :span="24">
                                <el-form-item label="新闻标题" prop="newsTitle">
                                    <el-input type="text" placeholder="请输入新闻标题" v-model="temp.newsTitle"
                                              size="mini"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="新闻来源" prop="newsSource">
                                    <el-input type="text" placeholder="请输入新闻来源" v-model="temp.newsSource"
                                              size="mini"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="新闻类型" prop="newsType">
                                    <el-select v-model="temp.newsType" placeholder="请选择" size="mini" clearable>
                                        <el-option v-for="item in newsTypeOptions" :key="item.value" :label="item.label"
                                                   :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="排序">
                                    <el-input type="number" placeholder="请输入排序" v-model="temp.newsRank"
                                              size="mini"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="阅读数">
                                    <el-input type="number" placeholder="请输入阅读数" v-model="temp.readAmount"
                                              size="mini"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="时间" prop="newsTime">
                                    <el-date-picker
                                            class="search-input"
                                            v-model="temp.newsTime"
                                            type="date"
                                            value-format="yyyy-MM-dd" size="small" clearable>
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>

                            <el-col :span="24">
                                <el-form-item label="楼盘Id"  v-if="temp.newsType === 'indexPicture'">
                                    <el-input type="number" placeholder="请输入楼盘Id" v-model="temp.newsLink"
                                              size="mini"></el-input>
                                </el-form-item>
                            </el-col>


                            <el-col :span="24">
                                <el-form-item label="图片">
                                    <el-upload action="https://upload.qiniup.com" class="avatar-uploader"
                                               :on-success="handleSuccess_small"
                                               :show-file-list="false" :before-upload="beforeUpload"
                                               :data="uploadData" accept="image/*">
                                        <img v-if="newsPicture" :src="newsPicture" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>

                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane label="富文本" name="second">
                        <tinymce v-model="temp.newsContent" :height="300" v-if="dialogFormVisible"/>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

            <div slot="footer">
                <el-button v-if="dialogStatus==='create'" type="primary" @click="create(temp)"
                           size="mini" :loading="tempLoading">提 交
                </el-button>
                <el-button v-else type="primary" @click="update(temp)" size="mini" :loading="tempLoading">提 交
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import newsApi from "api/news";
    import sassApi from "api/saasService";
    import common from "utils/common";
    import Tinymce from "@/components/Tinymce";

    export default {
        components: {Tinymce},
        data() {
            return {
                tabPosition: "left",  //tab导航位置
                tabValue: "first",
                listHeight: 0,  //动态列表高度
                totalElements: 0,   //总条数
                currentPage: 1,     //当前页
                list: null,       //列表
                tempLoading: false, //提交加载动画

                //搜索
                listQuery: {
                    page: 1,
                    pageSize: 10,
                    newsType: "",
                    newsTitle: "",
                    cityId: sessionStorage.getItem('ledaoCityId')
                },

                newsTypeOptions: [
                    {
                        label: "楼市情报局",
                        value: "flash"
                    },
                    {
                        label: "房产公开课",
                        value: "policy"
                    },
                    {
                        label: "首页图片",
                        value: "indexPicture"
                    },
                    {
                        label: "轮播图片",
                        value: "banner"
                    }
                ],


                //添加/修改
                dialogFormVisible: false,
                textMap: {
                    update: "编辑",
                    create: "创建"
                },
                dialogStatus: null, //添加/修改状态
                dialogFormVisibleLoading: false, //弹出框加载动画
                newsPicture: "",
                uploadData: {
                    key: "",
                    token: ""
                },
                temp: {
                    keyId: "",
                    newsType: "",
                    newsTitle: "",
                    newsPicture: null,
                    newsSource: "",
                    newsLink: "",
                    newsTime: "",
                    readAmount: "",
                    newsContent: "",
                    newsRank: "",
                    cityId: sessionStorage.getItem('ledaoCityId')
                },
                tempRules: {
                    // 验证规则
                    newsType: [{required: true, message: "请选择新闻类型", trigger: "blur"}],
                    newsTitle: [{required: true, message: "请填写新闻标题", trigger: "blur"}],
                    // newsPicture: [{required: true, message: "请上传图片", trigger: "blur"}],
                    newsSource: [{required: true, message: "请填写新闻来源", trigger: "blur"}],
                    // newsLink: [{required: true, message: "请填写新闻链接", trigger: "blur"}],
                    // newsTime: [{required: true, message: "请填写时间", trigger: "blur"}],
                },
            };
        },

        methods: {
            del(keyId) {
                this.$confirm("您确定删除当前数据吗？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    newsApi.deleted(keyId).then(res => {
                        if (res.code === 1) {
                            this.$notify({
                                title: "成功",
                                message: "删除成功",
                                type: "success",
                                customClass: "success",
                            });
                            this.getList();
                        } else {
                            this.$notify.error({
                                title: "错误",
                                message: res.msg,
                                customClass: "error",
                            });
                        }
                    });
                });
            },

            handleSuccess_small(res, file) {
                this.newsPicture = "https://testqn.weilong1993.com/" + res.key;
            },
            beforeUpload(file) {
                let self = this;
                let parts = file.name.split(".");//split() 方法用于把一个字符串分割成字符串数组。
                let fileType = parts[parts.length - 1];
                return sassApi.getUploadToken().then(function (res) {
                    self.uploadData.token = res.data;
                    self.uploadData.key = common.getNowStr() + "." + fileType;
                });
            },


            //提交数据清空
            resetTemp() {
                this.temp.newsTime = "";
                this.temp.newsType = "";
                this.temp.readAmount = "";
                this.temp.newsTitle = "";
                this.temp.newsSource = "";
                this.temp.newsPicture = "";
                this.temp.newsLink = "";
                this.temp.newsRank = "";
                this.newsPicture = "";

                this.$nextTick(() => {
                    this.$refs["temp"].clearValidate();   //对表单验证进行重置。
                });
            },

            //打开弹窗
            openDialog(dialogStatus, row) {
                this.dialogStatus = dialogStatus;
                this.dialogFormVisible = true;
                this.resetTemp();
                if (dialogStatus === "update") {
                    this.temp = Object.assign({}, row);
                    this.newsPicture = this.temp.newsPicture;
                }
            },


            //添加
            create() {
                this.temp.newsPicture = this.newsPicture;
                if (!this.temp.newsPicture) {
                    this.$notify.warning({
                        title: "提示",
                        message: "请上传图片",
                        customClass: "warning",
                        duration: 1500,
                    });
                    return;
                }
                this.$refs.temp.validate(valid => {
                    if (valid) {
                        this.tempLoading = true;

                        if (this.temp.newsContent) {
                            const reg = new RegExp( '<p>&nbsp;</p>' , "g" );
                            this.temp.newsContent = this.temp.newsContent.replace(reg,'<p style="height: 30px">&nbsp;</p>');

                            const reg1 = new RegExp( '<strong>' , "g" );
                            this.temp.newsContent = this.temp.newsContent.replace(reg1,'<strong style="font-weight: 700">');

                            const reg2 = new RegExp( '&nbsp;' , "g" );
                            this.temp.newsContent = this.temp.newsContent.replace(reg2,'<span style="display: inline-block;color: transparent;opacity: 0">a</span>');
                        }
                        newsApi.add(this.temp).then(res => {
                            let self = this;
                            setTimeout(function () {
                                self.tempLoading = false;
                            }, 2000);
                            if (res.code === 1) {
                                this.$notify({
                                    title: "成功",
                                    message: "添加成功",
                                    type: "success",
                                    customClass: "success",
                                    duration: 1500
                                });
                                this.getList();
                                this.resetTemp();
                                this.dialogFormVisible = false;
                            } else {
                                this.$notify.error({
                                    title: "失败",
                                    message: res.msg,
                                    customClass: "error",
                                    duration: 1500
                                });
                            }
                        });
                    } else {
                        this.$notify.warning({
                            title: "信息不完整",
                            message: "请完整填写信息",
                            customClass: "warning",
                            duration: 1500
                        });
                    }
                });
            },

            //修改
            update() {
                this.temp.newsPicture = this.newsPicture;
                if (!this.temp.newsPicture) {
                    this.$notify.warning({
                        title: "提示",
                        message: "请上传图片",
                        customClass: "warning",
                        duration: 1500,
                    });
                    return;
                }
                this.$refs.temp.validate(valid => {
                    if (valid) {
                        this.tempLoading = true;

                        if (this.temp.newsContent) {
                            const reg = new RegExp( '<p>&nbsp;</p>' , "g" );
                            this.temp.newsContent = this.temp.newsContent.replace(reg,'<p style="height: 30px">&nbsp;</p>');

                            const reg1 = new RegExp( '<strong>' , "g" );
                            this.temp.newsContent = this.temp.newsContent.replace(reg1,'<strong style="font-weight: 700">');

                            const reg2 = new RegExp( '&nbsp;' , "g" );
                            this.temp.newsContent = this.temp.newsContent.replace(reg2,'<span style="display: inline-block;color: transparent;opacity: 0">a</span>');
                        }
                        newsApi.update(this.temp).then(res => {
                            let self = this;
                            setTimeout(function () {
                                self.tempLoading = false;
                            }, 2000);
                            if (res.code === 1) {
                                this.$notify({
                                    title: "成功",
                                    message: "修改成功",
                                    type: "success",
                                    customClass: "success",
                                    duration: 1500
                                });
                                this.getList();
                                this.resetTemp();
                                this.dialogFormVisible = false;

                            } else {
                                this.$notify.error({
                                    title: "失败",
                                    message: res.msg,
                                    customClass: "error",
                                    duration: 1500
                                });
                            }
                        });
                    } else {
                        this.$notify.warning({
                            title: "信息不完整",
                            message: "请完整填写信息",
                            customClass: "warning",
                            duration: 1500,
                        });
                    }
                });
            },

            //列表
            getList() {
                newsApi.pageList(this.listQuery).then(res => {
                    this.list = res.data.content.map((d, i) => {
                        d.index = (this.currentPage - 1) * this.listQuery.pageSize + i + 1;
                        return d;
                    });
                    this.totalElements = res.data.totalElements;
                });
            },

            search() {
                this.listQuery.page = this.currentPage = 1;
                this.getList();
            },
            //控制列表显示条数
            handleSizeChange(val) {
                this.listQuery.page = 1;
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange() {
                this.listQuery.page = this.currentPage;
                this.getList();
            },

        },

        mounted() {
            this.$nextTick(() => {
                this.listHeight = this.$refs.main.offsetHeight - 175;
                let self = this;
                window.addEventListener("resize", function () {
                    self.listHeight = self.$refs.main.offsetHeight - 175;
                });
            });
        },

        created() {
            this.getList();
        },
    }
    ;
</script>